#!/usr/bin/env bash
set -e
# ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
# Function :CentOS7.X 安装/管理 mysql
# Platform :RedHatEL7.x Based Platform
# Version  :1.01
# Date     :2022-10-14
# Author   :mugoLH
# Contact  :hxsaj@126.com
# Company  :
# depend on:
# ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----

#  脚本引用 Import the script
# ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----

#  变量列表 List of common variables
# ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
# 下载的源站
Choices_Mirror=""

# 已被此脚本位置参数2代替
#Downloads_bin_file_address="https://mirrors.ustc.edu.cn/mysql-ftp/Downloads/MySQL-5.7/mysql-5.7.38-linux-glibc2.12-x86_64.tar.gz"


#  函数列表 Function list
# ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
info_p(){  printf "\e[1;32;40m%-12s\e[0m %-1s\n\e[0m" "${1}" "${2}"  >&1 ;}
tips_p(){  printf "\e[1;36;40m%-5s\e[0m %-1s\n\e[0m"  "${1}" "${2}"  >&1 ;}
error_p(){ printf "\e[1;35;40m%-12s\e[0m %-1s\n\e[0m" "${1}" "${2}"  >&1 ;}

#  获取下载的源站URL，mirror_URL
function print_mirrors_URL(){
	# 源站清单文件
	mirror_url_file=${1}

	# 打印源站清单
	if [[ -z ${mirror_url_file} ]];then
		error_p "[ ERROR   ]:" "需要指定源站URL清单！"
	elif [[ ! -f ${mirror_url_file}  ]]; then
		error_p "[ WARNING ]:" "不存在主机文件 ${mirror_url_file}，请检查！"
		return $?
	else
		egrep -v "^$|^#" ${mirror_url_file} |awk '{print$1,$2,$3}' |awk '$0=NR") "$0' |\
		awk '
		BEGIN{
			print "  ----------------------------------------------------------------------------";
			print "  | 序号 |  源站名  |                             URL                          |";
			print "  ----------------------------------------------------------------------------";
		}
		{
			printf "     %-5s %-5s %-10s\n",$1,$2,$3;
		}
		END{
			print  "  ----------------------------------------------------------------------------";
		}'
	fi

	# 获取源站个数
	mirror_nu=$(egrep -v "^$|^#" ${mirror_url_file} | wc -l)

	# 选择源站
	read -t 30 -p  "  选择源站[默认为 1]：" Choices_Mirror

	# 默认源站
	if [ -z ${Choices_Mirror} ];then
		export Choices_Mirror=1
	fi

	# 判断输入的合法性（必须是数字，并且是源站个数之内）
	if echo ${Choices_Mirror} |grep -wq "^[0-9]\{1,\}" ;then
		if [[ ${Choices_Mirror} -le ${mirror_nu} ]] && [[ ${Choices_Mirror} -gt 0 ]];then
			export Choices_Mirror
			export mirror_URL=$(egrep -v "^$|^#" ${mirror_url_file} | sed -n "${Choices_Mirror}p" | awk '{print$2}')
		else
			error_p "[ WARNING ]:" "源站选择错误，请重新选择："
			print_mirrors_URL ${mirror_url_file}
		fi
	elif [[ ${Choices_Mirror} == "q" ]] || [[ ${Choices_Mirror} == "Q" ]] ;then
		echo -e "\n  再见！欢迎下次继续使用！\n"
		return 0
		#exit 0
	else
		error_p "[ WARNING ]:" "输入错误，请输入源站序号："
		print_mirrors_URL ${mirror_url_file}
	fi
}

#  检索 Mysql 版本
function mysql_get_download_version(){
	TMP_version_file=./.tmp.mysql_version

	# 获取下载的详细版本和主板本号 Mysql_Download_version Major_Version_Number
    get_mysql_in_list(){
    	TMP_version_file=${1}

    	# 打印可选下载的版本
    	awk '$0=NR") "$0' ${TMP_version_file} |\
    	awk '
    	BEGIN{
    		print "  --------------------------------------------------";
    		print "  | 序号 |  Mysql 版本                               |";
    		print "  --------------------------------------------------";
    	}
    	{
    		printf "     %-4s %-24s\n",$1,$2;
    	}
    	END{
    		print  "  --------------------------------------------------";
    	}'
    	# 获取临时版本清单中所有的版本个数
    	Mysql_list_nu=$(egrep -v "^$|^#" ${TMP_version_file} | wc -l)
    	# 选择下载的版本
    	read -p  "  选择需要下载的版本（输入序号即可）：" Choices_version_download
    	# 判断输入的合法性（必须是数字，并且是版本个数之内）
    	if echo ${Choices_version_download} |grep -wq "^[0-9]\{1,\}" ;then
    		if [[ ${Choices_version_download} -le ${Mysql_list_nu} ]] && [[ ${Choices_version_download} -gt 0 ]];then
    			export Mysql_Download_version=$(egrep -v "^$|^#" ${TMP_version_file}| sed -n "${Choices_version_download}p" | awk '{print$1}')
    		else
    			error_p "[ WARNING ]:" "版本序号选择错误，请重新选择："
    			get_mysql_in_list ${TMP_version_file}
    		fi
    	else
    		error_p "[ WARNING ]:" "版本序号选择错误,请输入版本序号："
    		get_mysql_in_list ${TMP_version_file}
    	fi
    	# 获取主板本号
    	export Major_Version_Number=$(echo ${Mysql_Download_version}|awk -F "-" '{print$2}'|awk -F "." '{print$1"."$2}')
    }

	# 清空版本清单
	> ${TMP_version_file}

	# 获取版本清单
	if [[ ${Choices_Mirror} -eq 1 ]] || [[ ${Choices_Mirror} -eq 5 ]];then
		for i in $(curl -s ${mirror_URL}/|grep MySQL-[0-9]|awk -F "\"" '{print$2}'|awk -F "/" '{print$1}');do
			curl -s ${mirror_URL}/${i}/|awk -F "\"" '{print$2}'|egrep mysql-[0-9].[[0-9].[0-9]\{1,\}.tar.gz.md5|awk -F ".t" '{print$1}' >> ./.tmp.mysql_version
		done
	else
		for i in $(curl -s ${mirror_URL}/|grep MySQL-[0-9]|awk -F "\"" '{print$6}'|awk -F "/" '{print$1}');do
			curl -s ${mirror_URL}/${i}/|awk -F "\"" '{print$6}'|egrep mysql-[0-9].[[0-9].[0-9]\{1,\}.tar.gz.md5|awk -F ".t" '{print$1}' >> ./.tmp.mysql_version
		done
	fi

	#  选择下载的版本
	get_mysql_in_list ./.tmp.mysql_version

	#
}





# 检查wget命令
function wget_chack(){
	if [[ $(whereis wget | wc -l) -ne 1 ]];then
		echo -e "[ 安装wget ]: " && yum -y -q install wget
	fi
}

# 下载 mysql 二进制文件
function Mysql_Download(){





# 下载 mysql 二进制文件
function wget_download(){
	Download_URL=${1}
	if [[ $(whereis wget | wc -l) -eq 1 ]];then
		echo -e "[ 下载文件 ]：" && wget -c ${Download_URL} --no-check-certificate
	else
		wget_chack
	fi
}
# 安装 mysql 二进制文件
function mysql_install(){
	install_dir=${1}
	BintarFile_or_DownloadURL=${2}

	if [[ $# -eq 2 ]];then
		if [[ ! -d ${install_dir} ]];then
			echo -e "创建安装目录：${install_dir}"
			mkdir -p ${install_dir}
		fi

		if [[ -f ${BintarFile_or_DownloadURL} ]];then
			Bin_tar_file=${BintarFile_or_DownloadURL}
		else
			if [[ $(curl -I -m 10 -o /dev/null -s -w %{http_code} ${BintarFile_or_DownloadURL} ) -eq 200 ]];then
				# 下载 mysql 二进制文件
				wget_chack
				wget_download ${BintarFile_or_DownloadURL}
				# 确定下载文件的的名字
				Bin_tar_file=$(echo "${BintarFile_or_DownloadURL}" | awk -F "/" '{print$NF}')
			else
				echo -e "不是tar.gz压缩包 或 文件下载URL错误！"
				exit 2
			fi
		fi
		# 解压二进制到指定目录
		echo -e "[ 解压文件 ]: ${install_dir}" && tar -zxf ${Bin_tar_file} -C ${install_dir}/

		# 修改目录名字，便于使用
		Bin_Basename=$(tar -ztf ${Bin_tar_file} | head -5 | awk -F "/" '{print$1}' |sort -nr |uniq)
		Base_Mysql=$(echo ${Bin_Basename} |awk -F "-" '{print$1"-"$2}')
		mv ${install_dir}/${Bin_Basename} ${install_dir}/${Base_Mysql}

		# 创建配置目录和数据目录
		mkdir -p ${install_dir}/${Base_Mysql}/{data,conf}

		# 生成配置文件
		echo -e "[ 生成配置 ]：${install_dir}/${Base_Mysql}/conf/my.cnf "
		cat > ${install_dir}/${Base_Mysql}/conf/my.cnf << EOF
[client]
default-character-set  = utf8mb4

[mysql]
port                   = 3306
socket                 = ${install_dir}/${Base_Mysql}/data/mysql.sock
default-character-set  = utf8mb4

[mysqld]
port                   = 3306
default_storage_engine = InnoDB
basedir                = ${install_dir}/${Base_Mysql}
datadir                = ${install_dir}/${Base_Mysql}/data
socket                 = ${install_dir}/${Base_Mysql}/data/mysql.sock
character-set-client-handshake = FALSE
character-set-server   = utf8mb4
collation-server       = utf8mb4_unicode_ci
init_connect           = 'SET NAMES utf8mb4'
max_connections        = 2000
max_allowed_packet     = 128M
innodb_file_per_table  = 1
tmp_table_size         = 134217728
max_heap_table_size    = 134217728
lower_case_table_names = 1

log-bin                = mysql-bin
max_binlog_size        = 1024M
expire_logs_days       = 1
log_slave_updates      = 1
server-id              = 1

sql_mode=STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION

EOF

		# 创建运行账号
		if ! id mysql >/dev/null 2>&1;then
			useradd mysql
		fi

		# 授权相关目录权限
		chown -R mysql.mysql ${install_dir}

		# 写入环境变量
		echo -e "[ 环境变量 ]：/etc/bashrc"
		echo -e "export PATH=${install_dir}/${Base_Mysql}/bin:\$PATH" >> /etc/bashrc

		# 环境变量生效
		source /etc/bashrc

		# 软连接sock文件
		ln -s ${install_dir}/${Base_Mysql}/data/mysql.sock /tmp/mysql.sock

		# 初始化 mysql
		echo -e "[ 初始服务 ]:"
		mysqld --defaults-file=${install_dir}/${Base_Mysql}/conf/my.cnf --user=mysql --initialize > /tmp/${Base_Mysql}.install.tmp 2>&1

		# 启动mysql
		echo -e "[ 启动mysql ]: ${install_dir}/${Base_Mysql}/bin/mysqld_safe --defaults-file=${install_dir}/${Base_Mysql}/conf/my.cnf --user=mysql &"
		${install_dir}/${Base_Mysql}/bin/mysqld_safe --defaults-file=${install_dir}/${Base_Mysql}/conf/my.cnf --user=mysql &

		# 修改初始密码
		sleep 5
		${install_dir}/${Base_Mysql}/bin/mysql -uroot -p$(awk '/root@localhost/{print$NF}' /tmp/${Base_Mysql}.install.tmp) --connect-expired-password -sNe "set password = password('594hxs');" 2>/dev/null
		echo -e "[ 部署完成 ]: 数据库root密码：594hxs，请执行: source /etc/bashrc && mysql -uroot -p594hxs 登录数据库执行计划操作！"
	fi
}


if [[ $# -eq 2 ]];then
	install_dir=${1}
	BintarFile_or_DownloadURL=${2}
	mysql_install ${install_dir} "${BintarFile_or_DownloadURL}"
else
	echo -e "[ 使用方法 ]：$0 \"[安装位置{字符串}]\" \"[下载二进制的URL地址 | 二进制压缩包绝对路径]\""
fi


#  操作选项
function change_opera(){
	echo -e "\n操作内容："
	tips_p 1） Mysql 下载
	tips_p 2） Mysql 安装
	tips_p 3） Mysql 修改 root 密码
	tips_p 4） Mysql 新建用户
	tips_p 5） Mysql 新增从库（半同步复制）
	tips_p 6） Mysql 新增备库（异步复制）
	tips_p 7） Mysql 服务拓普信息
	tips_p q） 退出
	read -p "选择（输入序号）：" ch_op
	case C${ch_op} in
		C1 ) printf_app;  change_opera  ;;
		C2 ) create_mysql;change_opera  ;;
		C3 ) delete_app;  change_opera  ;;
		C4 ) create_db;   change_opera  ;;
		C5 ) create_user; change_opera  ;;
		C6 ) backup_app;  change_opera  ;;
		C7 ) restore_app; change_opera  ;;
		Cq ) exit		   	            ;;
		C* ) change_opera  		        ;;
	esac
}


change_opera

